//
//  CommonHelper.swift
//  CommonFoundation
//
//  Created by raniys on 1/5/18.
//

import Foundation

public func delay(_ time: Double, execute: @escaping () -> Void) {
    if time > 0 {
        DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: execute)
    } else {
        DispatchQueue.main.async(execute: execute)
    }
}

/// Convert NSObject array to String array. i.e.: [1,2,3]->['1','2','3']
public func bridgeObjToStringArray(array: [NSObject]) -> [String?] {
    var newArray = [String?]()
    for object in array
    {
        newArray.append(object as? String)
    }
    return newArray
}

public func report_memory() {
    var taskInfo = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
    let kerr: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
        $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
            task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
        }
    }
    
    if kerr == KERN_SUCCESS {
        print("Memory used in bytes: \(taskInfo.resident_size)")
    }
    else {
        print("Error with task_info(): " +
            (String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error"))
    }
}

/// Convert int number to calculated size string
///
/// - Parameter size: original size int value
/// - Returns: Calculated size string
public func stringSize(_ size: Int) -> String {
    
    var r = ""
    
    let kb = size.kb
    let mb = size.mb
    let gb = size.gb
    if gb >= 1 {
        r = String(format: "%.2fGB", gb)
    } else if mb >= 1 {
        r = String(format: "%.2fMB", mb)
    } else if kb >= 1 {
        r = String(format: "%.2fKB", kb)
    } else {
        r = String(format: "%dB", size)
    }
    
    return r
}

let PHOTO_COMPRESSION_QUALITY_RATIO: CGFloat = 0.6
let PHOTO_MAX_SIDE_LENGTH: CGFloat = 4096
let PHOTO_MIN_BYTE_SIZE: Double = 1.5 * 1024 * 1024

public extension UIImage {
    
    func resizeForUploadOSS() -> Data? {
        let image = self.imageResizeWithConstantSize(sizeValue: PHOTO_MAX_SIDE_LENGTH)
        return image.imageRepresentationWith(ratio: PHOTO_COMPRESSION_QUALITY_RATIO, baseSizeByte: Int(PHOTO_MIN_BYTE_SIZE))
    }
    
}
